package com.cs.beneficios.web.action;

import com.cs.beneficios.business.entity.BeneficiarioDAO;
import com.cs.beneficios.business.model.BeneficiarioVO;
import com.cs.beneficios.common.ConnectionFactory;
import com.cs.beneficios.common.util.Utility;
import com.cs.beneficios.web.form.IngresarBeneficiarioForm;
import com.cs.paoyer.administration.business.model.UserVO;
import com.cs.paoyer.administration.exception.AdministrationUserException;
import com.cs.paoyer.administration.util.AccessControl;
import com.cs.paoyer.common.exception.CommonUserException;
import com.cs.paoyer.common.exception.UserException;

import java.io.IOException;

import java.sql.SQLException;

import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class IngresarBeneficiarioAction extends Action {
	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		ActionMessages messages = new ActionMessages();
		try {
			AccessControl access = new AccessControl();
			access.validateAccess(mapping, request, response);

			// ConnectionFactory cf = new
			// ConnectionFactory("beneficios","beneficios");
			ConnectionFactory cf = new ConnectionFactory();

			BeneficiarioVO objBeneVO = new BeneficiarioVO();
			IngresarBeneficiarioForm buscarForm = (IngresarBeneficiarioForm) form;
			String strDocumento = buscarForm.getDocumento();
			HttpSession session = request.getSession();
			// request.setAttribute("numeroDocumento",strDocumento);
			// request.setAttribute("tipoDocumento",strTipoDocumento);
			session.removeAttribute("beneficiarios");
			session.removeAttribute("Option");
			session.removeAttribute("InsertGrupoFamiliar");
			Collection beneficiarios = null;
			session.setAttribute("msg", "");

			if (request.getParameter("search") != null) {
				if (strDocumento != null) {
					objBeneVO.setNumeroDocumento(buscarForm.getDocumento());
					objBeneVO.setTipoDocumento(buscarForm.getTipoDocumento());
					objBeneVO.setNombre1(buscarForm.getPrimer_nombre());
					objBeneVO.setNombre2(buscarForm.getSegundo_nombre());
					objBeneVO.setPrimerApellido(buscarForm.getPrimerApellido());
					objBeneVO.setSegundoApellido(buscarForm
							.getSegundoApellido());
					if (buscarForm.getFechaNacimiento().equals("Dia/Mes/Ano"))
						objBeneVO.setFechaNacimiento("");
					else
						objBeneVO.setFechaNacimiento(buscarForm
								.getFechaNacimiento());

					BeneficiarioDAO objBeneDAO;
					try {
						objBeneDAO = new BeneficiarioDAO(cf);
						beneficiarios = objBeneDAO.findBeneficiarioByCriterea(
								objBeneVO, "ingresarBeneficiario");
						System.err.println("busque en el sistema sub");
						cf.closeConnection(objBeneDAO.getConn());
					} catch (SQLException e) {
						System.err.println("/******** TDSUB - cwsub");
						e.printStackTrace();
						System.err.println("TDSUB - cwsub ********/");
					}

					if (beneficiarios != null) {						// IF 1
						if (beneficiarios.size() > 0) {					// IF 2
							session.setAttribute("beneficiarios", beneficiarios);
							try {
								objBeneDAO = new BeneficiarioDAO(cf);
								List beneEncontrado = (List) beneficiarios;
								BeneficiarioVO beneBDBeneficios = (BeneficiarioVO) beneEncontrado
										.get(0);
								UserVO user = (UserVO) session
										.getAttribute("userInfo");
								String terminalAddress = request
										.getRemoteAddr();
								beneBDBeneficios.setUpdateUser(user.getName());
								beneBDBeneficios.setUpdateTerminal("WEB="
										+ terminalAddress);
								Calendar c = Calendar.getInstance();
								SimpleDateFormat dateFormat = new SimpleDateFormat(
										"dd/MM/yyyy");
								beneBDBeneficios.setUpdateDate(dateFormat
										.format(c.getTime()));
								int guardar = objBeneDAO
										.actualizarBeneficiario(beneBDBeneficios);
								cf.closeConnection(objBeneDAO.getConn());
							} catch (SQLException e) {
								System.err.println("/******** TDSUB - cwsub");
								e.printStackTrace();
								System.err.println("TDSUB - cwsub ********/");
							}
						} else {											// END IF 2		
							// BUSQUEDA EN SISBEN
							try {
								objBeneDAO = new BeneficiarioDAO(cf);
								beneficiarios = objBeneDAO
										.findBeneficiarioSisben(objBeneVO);
								cf.closeConnection(objBeneDAO.getConn());
							} catch (SQLException e) {
								System.err.println("/******** TDSUB - cwsub");
								e.printStackTrace();
								System.err.println("TDSUB - cwsub ********/");
								request.setAttribute(
										"msg",
										"Error en busqueda SISBEN: "
												+ e.getMessage());
							}
							if (beneficiarios != null && beneficiarios.size() > 0 ) {					// IF 3			
									List beneSisben = (List) beneficiarios;
									objBeneVO = (BeneficiarioVO) beneSisben
											.get(0);
									// CAMBIA EL FORMATO DE TIPO NUMERICO EN EL
									// SISBEN (1,2,3,4) HACIA EL ALFANUMERICO
									// (C,T,R,E)
									request.setAttribute(
											"tipoDocumento",
											Utility.deformatSisbenDocument(objBeneVO
													.getTipoDocumento()));
									request.setAttribute("numeroDocumento",
											objBeneVO.getNumeroDocumento());
									request.setAttribute("nombre1", objBeneVO
											.getNombre1().trim());
									if (objBeneVO.getNombre2() != null)
										request.setAttribute("nombre2",
												objBeneVO.getNombre2().trim());
									else
										request.setAttribute("nombre2",
												objBeneVO.getNombre2());

									request.setAttribute("apellido1", objBeneVO
											.getPrimerApellido().trim());
									if (objBeneVO.getSegundoApellido() != null)
										request.setAttribute("apellido2",
												objBeneVO.getSegundoApellido()
														.trim());
									else
										request.setAttribute("apellido2",
												objBeneVO.getSegundoApellido());
									try {
										String fenato[] = objBeneVO
												.getFechaNacimiento()
												.split("/");
										request.setAttribute("dia", fenato[0]);
										request.setAttribute("mes", fenato[1]);
										request.setAttribute("ano", fenato[2]);
									} catch (Exception err) {
										request.setAttribute("dia", "Dia");
										request.setAttribute("mes", "Mes");
										request.setAttribute("ano", "Ano");
									}
									request.setAttribute("sexo",
											objBeneVO.getSexo());
									request.setAttribute("msg",
											"El beneficiario se ha encontrado en la base de datos del Sisben.");
									request.setAttribute("beneficiarioSisben",
											beneficiarios);
									try {
										objBeneDAO = new BeneficiarioDAO(cf);
										Collection grupo_familiar = objBeneDAO
												.getGrupoFamiliarSisben(
														objBeneVO
																.getFichaSisben(),
														objBeneVO.getHogar());
										cf.closeConnection(objBeneDAO.getConn());
										if (grupo_familiar.size() > 0) {
											request.setAttribute(
													"grupo_familiar",
													grupo_familiar);
											session.setAttribute(
													"InsertGrupoFamiliar",
													grupo_familiar);
										}

									} catch (SQLException err) {
										System.err
												.println("/******** TDSUB - cwsub");
										err.printStackTrace();
										System.err
												.println("TDSUB - cwsub ********/");
									}
									return mapping.findForward("success");
								} else {									// END IF 3
									request.setAttribute("tipoDocumento",
											buscarForm.getTipoDocumento());
									request.setAttribute("numeroDocumento",
											strDocumento);
									request.setAttribute("nombre1",
											buscarForm.getPrimer_nombre());
									request.setAttribute("nombre2",
											buscarForm.getSegundo_nombre());
									request.setAttribute("apellido1",
											buscarForm.getPrimerApellido());
									request.setAttribute("apellido2",
											buscarForm.getSegundoApellido());
									request.setAttribute("dia", buscarForm.getDia());
									request.setAttribute("mes", buscarForm.getMes());
									request.setAttribute("ano", buscarForm.getAno());
									return mapping.findForward("fail");
								}																															
							}															
					} else{													//END IF 1
						request.setAttribute("tipoDocumento",
								buscarForm.getTipoDocumento());
						request.setAttribute("numeroDocumento",
								strDocumento);
						request.setAttribute("nombre1",
								buscarForm.getPrimer_nombre());
						request.setAttribute("nombre2",
								buscarForm.getSegundo_nombre());
						request.setAttribute("apellido1",
								buscarForm.getPrimerApellido());
						request.setAttribute("apellido2",
								buscarForm.getSegundoApellido());
						request.setAttribute("dia", buscarForm.getDia());
						request.setAttribute("mes", buscarForm.getMes());
						request.setAttribute("ano", buscarForm.getAno());
						return mapping.findForward("fail");
					}		 
				} // FIN IF DOCUMENTO != NULL
			}// FIN IF PRINCIPAL (SEARCH != NULL)
		} catch (UserException ue) {
			messages.add("msgWarn", new ActionMessage("loginForm.message."
					+ ue.getExceptionVO().getId()));
			saveMessages(request, messages);
			if (ue.getExceptionVO().getId() == AdministrationUserException.ENDED_SESSION) {
				response.sendRedirect(request.getContextPath() + "/index.jsp");
			} else if (ue.getExceptionVO().getId() == CommonUserException.NOT_ALLOWED_RESOURCE) {
				response.sendRedirect(request.getContextPath()
						+ "/admin/tile/invalidatedResource.jsp");
			} else {
				return mapping.getInputForward();
			}

		}

		return mapping.findForward("success");
	}
}